package cn.fboost.mtos.util;

import cn.fboost.mtos.dto.internal.Session;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class ContextHolderUtil {
    public static HttpServletRequest mockHttpServletRequest = null;

    public static HttpServletRequest getRequest() {
        return Objects.requireNonNullElseGet(mockHttpServletRequest,
                () -> ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest());
    }

    public static Session getCurrentSession() {
        return (Session) getRequest().getAttribute("current_session");
    }

    public static String getAccessToken() {
        String token = getRequest().getHeader("access-token");
        if (token.length() > 0) {
            return token;
        }

        return null;
    }
}
